package by.gravity.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils {

	public static boolean unpackZip(String inputPath, String outputDirecotry) {
		InputStream is;
		ZipInputStream zis;
		boolean result = false;
		try {
			String filename;
			is = new FileInputStream(inputPath);
			zis = new ZipInputStream(new BufferedInputStream(is));
			ZipEntry ze;
			byte[] buffer = new byte[512];
			int count;
			
			while ((ze = zis.getNextEntry()) != null) {
				filename = ze.getName();

				if (ze.isDirectory()) {
					File fmd = new File(outputDirecotry + "/" + filename);
					fmd.mkdirs();
					continue;
				}
				if(!folderCreated(outputDirecotry)){
					createFolder(outputDirecotry);
				}
				FileOutputStream fout = new FileOutputStream(outputDirecotry + "/" + filename);

				while ((count = zis.read(buffer)) != -1) {
					fout.write(buffer, 0, count);
				}

				fout.close();
				zis.closeEntry();
				if(!result){
					result = true;
				}
			}

			zis.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return result;
	}
	
	private static boolean folderCreated(String path){
		File file = new File(path);
		return file.exists();
	}
	
	private static void createFolder(String path){
		File file = new File(path);
		file.mkdir();
	}
}
